package com.etop.dao;

import com.etop.beans.Activity;
import com.etop.beans.Goods;
import com.etop.beans.ProFile;
import com.etop.beans.Pro_schedule;
import com.etop.beans.Project;
import com.etop.beans.User;
import com.etop.beans.User_project;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.web.multipart.MultipartFile;

public class ManagerDao {

    private SessionFactory sessionFactory;
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    /**
     * 将project的所有内容存到list中
     *
     * @return
     */
    public List<Project> listOfProject() {
        String checkSql = "from Project as pro order by pro.start_time desc";
        List<Project> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将pro_schedule的所有内容存入list中
     *
     * @return
     */
    public List<Pro_schedule> listOfProSchedule() {
        String checkSql = "from Pro_schedule as sche order by sche.time desc";
        List<Pro_schedule> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将user_project的所有内容存入list中
     *
     * @return
     */
    public List<User_project> listOfUserProject() {
        String checkSql = "from User_project";
        List<User_project> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listLeadersOfOneProject(Project pro) {
        String checkSql = "select u.userName from User as u,User_project as u_pro where u_pro.pro_id = ? and u_pro.isleader = 1 and u.id = u_pro.u_id";
        List<String> list = this.getSession().createQuery(checkSql).setParameter(0, pro.getId()).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listMembersOfOneProject(Project pro) {
        String checkSql = "select u.userName from User as u,User_project as u_pro where u_pro.pro_id = ? and u_pro.isleader = 0 and u.id = u_pro.u_id";
        List<String> list = this.getSession().createQuery(checkSql).setParameter(0, pro.getId()).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 删除项目编号为id的项目
     *
     * @param id
     */
    public void deleteOneProject(int id) {
        System.out.println("id:" + id);
        String hql = "delete User_project where pro_id = :pid";
        String hql2 = "delete Pro_schedule where p_id = :pid";
        this.getSession().createQuery(hql).setParameter("pid", id).executeUpdate();
        this.getSession().createQuery(hql2).setParameter("pid", id).executeUpdate();
        Project pro = (Project) this.getSession().load(Project.class, id);
        this.getSession().delete(pro);
    }

    /**
     * 处理上传文件
     *
     * @param multipartFile
     * @param proFile
     * @param contextPath
     */
    public void addProFile(MultipartFile multipartFile, ProFile proFile, String contextPath) {
        String fileName = UUID.randomUUID().toString() + "_" + multipartFile.getOriginalFilename();
        //创建保存文件的目录：主目录+LabRegistration+proFile+项目名
        String savePath = contextPath + "/WEBINF/ProFile/" + proFile.getProject().getName();
        File f = new File(savePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        System.out.println(f.getAbsolutePath());
        //同时在proFile中记录文件的位置以便写入数据库保存
        proFile.setFile(savePath + '/' + fileName);

        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(proFile.getFile()));
        } catch (IOException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.getSession().save(proFile);
    }

    /**
     * 取出所有名字中含有proName的文件
     *
     * @param proName
     * @return
     */
    public List<ProFile> listProFile(String proName) {
        return this.getSession().createQuery("from ProFile where project.name like ?").setParameter(0, "%" + proName + "%").list();
    }

    /**
     * 通过文件Id找到文件
     *
     * @param proFileId
     * @return
     */
    public ProFile loadProFileById(int proFileId) {
        return (ProFile) this.getSession().createQuery("from ProFile where id = :pid").setInteger("pid", proFileId).uniqueResult();
    }

    /**
     * 通过projectId找到对应的project
     *
     * @param projectId
     * @return
     */
    public Project loadProjectById(int projectId) {
        return (Project) this.getSession().createQuery("from Project where id = :pid").setInteger("pid", projectId).uniqueResult();
    }

    /**
     * 列出所有项目
     *
     * @return
     */
    public List<Project> listProject() {
        return this.getSession().createQuery("from Project").list();
    }

    /**
     * 添加活动
     *
     * @param act
     */
    public void addActivity(Activity act) {
        this.getSession().save(act);
    }

    /**
     * 返回id为aid的活动
     *
     * @param aid
     * @return
     */
    public Activity loadActivityById(int aid) {
        return (Activity) this.getSession().createQuery("from Activity where id = ?").setParameter(0, aid).uniqueResult();
    }

    /**
     * 更新活动信息
     *
     * @param act
     */
    public void updateActivity(Activity act) {
        this.getSession().update(act);
    }

    /**
     * 删除某一个活动
     *
     * @param act
     */
    public void deleteActivity(Activity act) {
        String sql = "delete from user_activity where act_id = ?";
        this.getSession().createSQLQuery(sql).setParameter(0, act.getId()).executeUpdate();
        this.getSession().delete(act);
    }

    /**
     * 列出所有名字中有关键字key的活动
     *
     * @param key
     * @return
     */
    public List<Activity> listActivity(String key) {
        return this.getSession().createQuery("from Activity where name like :key")
                .setParameter("key", '%' + key + '%').list();
    }
    /**
     * ccp
     *
     * @param userId
     * @return
     */
    public User loadUser(int userId) {
        String checkSql = "from User where id =:id";
        User user = (User) this.getSession().createQuery(checkSql)
                .setParameter("id", userId).uniqueResult();
        return user;
    }

    /**
     * 修改用户信息 ccp
     *
     * @param user
     * @return
     */
    public void updateInfo(User user) {
        Session session = this.getSession();
        User userUpdate = (User) session.load(User.class, user.getId());
        userUpdate.setAddress(user.getAddress());
        userUpdate.setBlog(user.getBlog());
        userUpdate.setEmail(user.getEmail());
        userUpdate.setGender(user.getGender());
        userUpdate.setGitAccount(user.getGitAccount());
        userUpdate.setTel(user.getTel());
        userUpdate.setUserGrade(user.getUserGrade());
        session.update(userUpdate);
    }

    /**
     * ccp 
     * 删除用户
     * @param userId
     */
    public void deleteUser(int userId) {
        String hql1 = "delete Borrow where user.id = :id";
        String hql2 = "delete Registration where u_id = :id";
        String hql3 = "delete User_activity where u_id = :id";
        String hql4 = "delete User_project where u_id = :id";
        this.getSession().createQuery(hql1).setParameter("id", userId).executeUpdate();
        this.getSession().createQuery(hql2).setParameter("id", userId).executeUpdate();
        this.getSession().createQuery(hql3).setParameter("id", userId).executeUpdate();
        this.getSession().createQuery(hql4).setParameter("id", userId).executeUpdate();
        User user = this.loadUser(userId);
        this.getSession().delete(user);
    }
}
